import pickle,json
import base64

# 1.json:   将python dict/list  <====> json字符串
carts_dict = {
    1: {
        2: {
            'count': 30,
            'selected': True
        }
    }
}
# 1.1 将 dict ==> json字符串  == 1, 2本来是 int 现在 被 "1","2"
json_carts_str = json.dumps(carts_dict)

# 1.2 将 json字符串 ==> dict/list
json_carts_dict = json.loads(json_carts_str)




class CookieSecret(object):
    # 加密
    @classmethod
    def dumps(cls, data):
        # 1.将数据装换成bytes
        data_bytes = pickle.dumps(data)
        # 2.将bytes使用base64序列化加密
        base64_bytes = base64.b64encode(data_bytes)
        # 3.将加密完毕的bytes以字符串类型输出
        base64_str = base64_bytes.decode()
        return base64_str

    # 2.pickler: 将python的对象   <====> bytes
    # 2.1 将 obj ==> =bytes
    pickle_carts_bytes = pickle.dumps(carts_dict)
    # 2.2 将 bytes ==> obj
    pickle_carts_dict = pickle.loads(pickle_carts_bytes)
    # 解密
    @classmethod
    def loads(cls, data):
        # 1.将数据解密转成bytes
        base64_bytes = base64.b64decode(data)
        # 2.将bytes转回原来的python类型
        pickle_data = pickle.loads(base64_bytes)
        return pickle_data

    encode_base_64 = base64.b64encode(pickle_carts_bytes)

    # 3.2 base64:  解码--参数 可以str 也可以是 bytes
    decode_base_64 = base64.b64decode(encode_base_64.decode())

    print(decode_base_64)
    print(type(decode_base_64))

    result = pickle.loads(decode_base_64)
    print(result)
    # encode_base_64 = base64.b64encode(pickle_carts_bytes)
    #
    # # 3.2 base64:  解码--参数 可以str 也可以是 bytes
    # decode_base_64 = base64.b64decode(encode_base_64.decode())
    #
    # print(decode_base_64)
    # print(type(decode_base_64))
    #
    # result = pickle.loads(decode_base_64)
    # print(result)